package com.web.task;

import com.web.config.KftPayCommConfig;
import com.web.config.KppAppPayConfiguration;
import com.web.dao.*;
import com.web.entity.*;
import com.web.kftsdk.api.KftPayConfigStorage;
import com.web.kftsdk.api.KftPayService;
import com.web.kftsdk.common.bean.PayRes;
import com.web.kftsdk.entity.KppAppPayRes;
import com.web.kftsdk.entity.KppTradeRecordQueryReq;;
import com.web.manager.CoreManager;
import com.web.manager.KftCoreManager;
import com.web.manager.jpush.SendJPushMessage;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

/**
 * @author xw
 * Created by Welcome Chen on 2018-08-13.
 */
@Component
@Configurable
@EnableScheduling
@Slf4j
public class KftFixOrderStatusJob {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private KftPayCommConfig kftPayCommConfig;
    @Autowired
    private MemberMapper memberMapper;
    @Autowired
    private AccountMapper accountMapper;
    @Autowired
    private StoreMapper storeMapper;
    @Autowired
    private RegionRecordMapper regionRecordMapper;
    @Autowired
    private ProfitConfigMapper profitConfigMapper;
    @Autowired
    private PoundageConfigMapper poundageConfigMapper;
    @Autowired
    private PlatformMapper platformMapper;
    @Autowired
    private MessageMapper messageMapper;
    @Autowired
    private KftCoreManager kftCoreManager;
    @Autowired
    private OrderGoodsMapper orderGoodsMapper;
    @Autowired
    private GoodsMapper goodsMapper;
    @Autowired
    private KppAppPayConfiguration kppAppPayConfiguration;

    @Scheduled(cron = "0/8 * * * * ?")
    public void queryOrderPayStatus() {

        List<Order> waitConfirmPayStatus = orderMapper.selectByPaytypeAndStatus();
        log.info( "未确认支付结果的订单数：" + waitConfirmPayStatus.size() );
        for (Order o : waitConfirmPayStatus) {
            try {
                //快付通支付订单查询
                KppTradeRecordQueryReq kppTradeRecordQueryReq = new KppTradeRecordQueryReq();
                kppTradeRecordQueryReq.setOriginalOrderNo( o.getOrderNum() );
                kppTradeRecordQueryReq.setMerchantId( kppAppPayConfiguration.getMerchantId() );
                KftPayConfigStorage kftPayConfigStorage = new KftPayConfigStorage();
                kftPayConfigStorage.setPackPath( kftPayCommConfig.getPackPath() );
                kftPayConfigStorage.setSftpPath( kftPayCommConfig.getSftpPath() );
                kftPayConfigStorage.setSftpHost( kftPayCommConfig.getSftpHost() );
                kftPayConfigStorage.setSftpUsername( kftPayCommConfig.getSftpUsername() );
                kftPayConfigStorage.setSftpPassword( kftPayCommConfig.getSftpPassword() );
                kftPayConfigStorage.setKeyPrivate( kftPayCommConfig.getKeyPrivate() );
                kftPayConfigStorage.setDevGateWay( kftPayCommConfig.getDevGateWay() );
                kftPayConfigStorage.setGateWay( kftPayCommConfig.getGateWay() );
                kftPayConfigStorage.init();
                KftPayService kftPayService = new KftPayService( kftPayConfigStorage );
                PayRes payRes = kftPayService.kppTradeRecordQuery( kppTradeRecordQueryReq );
                boolean payFlag = false;
                boolean isKft = false;
                String status = ((KppAppPayRes)payRes.getData()).getStatus();
                if (payRes.valid()) {
                    //交易查询成功
                    if (status.equals( "1" )) {
                        //交易成功
                        log.info( "订单：" + o.getOrderNum() + "支付成功" );
                        payFlag = true;
                    } else {
                        //交易失败
                        log.info( "订单：" + o.getOrderNum() + "支付失败" );
                        payFlag = false;
                    }

                } else {
                    //交易查询失败
                    log.info( "交易查询失败,失败详情:"+((KppAppPayRes)payRes.getData()).getFailureDetails());

                }

                Date date = new Date();
                if (payFlag) {
                    //支付成功
                    String orderNum = o.getOrderNum();
                    //消费者信息
                    Member member = memberMapper.selectByPrimaryKey( o.getmId() );
                    BigDecimal totalPrice = o.getTotalPrice().add( o.getTipPrice() );

                    CompanyReport companyReport = new CompanyReport();


                    if (o.getOrderType().equals( "online" )) {
                        //企业订单
                        //更新订单支付状态
                        Order update = new Order();
                        update.setStatus( 1 );
                        update.setId( o.getId() );
                        orderMapper.updateByPrimaryKeySelective( update );

                    } else {


                        //消费者账户信息
                        Account account = accountMapper.selectByMid( o.getmId() );

                        //商家店铺信息
                        Store store = storeMapper.selectByPrimaryKey( o.getStoreId() );
                        //商家账户信息
                        Account merchantAccount = accountMapper.selectByMid( store.getmId() );
                        //商户信息
                        Member merchant = memberMapper.selectByPrimaryKey( store.getmId() );

                        Member memberUp = null;
                        if (member.getInvitedCode() != null) {
                            //用户上线
                            memberUp = memberMapper.selectMyUp( member.getInvitedCode() );
                        }

                        Member merchantUp = null;
                        if (merchant.getInvitedCode() != null) {
                            //商户上线
                            merchantUp = memberMapper.selectMyUp( merchant.getInvitedCode() );
                        }

                        //店铺的省市区三级代理商获取
                        RegionRecord province = regionRecordMapper.selectProvince( store.getProvince() );
                        RegionRecord city = regionRecordMapper.selectProvinceAndCity( store.getProvince(), store.getCity() );
                        RegionRecord region = regionRecordMapper.selectProvinceAndCityAndRegion( store.getProvince(), store.getCity(), store.getRegion() );

                        //总的奖励分配
                        BigDecimal totalBonus = new BigDecimal( 0 );

                        //利润分配配置
                        ProfitConfig config = profitConfigMapper.selectByPrimaryKey( 1L );
                        //msk卖出配置
                        PoundageConfig poundageConfig = poundageConfigMapper.selectByPrimaryKey( 1L );
                        //平台账户信息
                        Platform platform = platformMapper.selectByPrimaryKey( 1L );

                        synchronized (this) {

                            //核心处理方法
                            kftCoreManager.coreOperation( o, totalPrice, totalBonus, o.getTransferPrice(), config, poundageConfig, platform, member, memberUp, account, merchant, merchantUp
                                    , province, city, region, date, store, companyReport );

                        }
                    }


                    //boolean flag=iUserOrderService.updateOrder(orderId);
                    //log.info("订单修改状态："+(flag?"成功":"失败"));
                    // 推送消息
                    Message message = new Message();
                    message.setModifyTime( date );
                    message.setCreateTime( date );
                    message.setContent( "尊敬的用户您使用支付宝或支付宝支付订单：" + orderNum + "，" + totalPrice + " 元。成功支付！" );
                    message.setTitle( "支付结果" );
                    message.setFrom( 0L );
                    message.setFromName( "系统" );
                    message.setTarget( member.getId() );
                    message.setTargetName( member.getNickName() );
                    messageMapper.insertSelective( message );
                    SendJPushMessage.jPushByMessage( message );

                } else {
                    //支付失败或订单未创建
                    //支付不成功回退订单锁定库存，删除订单，及订单明细
                    List<OrderGoods> orderGoods = orderGoodsMapper.selectByOrderId( o.getId() );
                    for (OrderGoods og : orderGoods) {
                        //回退库存
                        goodsMapper.numAdd( og.getNum(), o.getId() );
                    }

                    orderMapper.deleteByPrimaryKeyLogic( o.getOrderNum() );
                    Message message = new Message();
                    message.setModifyTime( date );
                    message.setCreateTime( date );
                    message.setContent( "尊敬的用户您支付订单：" + o.getOrderNum() + "，" + o.getTotalPrice().add( o.getTipPrice() ) + " 元。支付失败！" );
                    message.setTitle( "支付结果" );
                    message.setFrom( 0L );
                    message.setFromName( "系统" );
                    message.setTarget( o.getmId() );
                    message.setTargetName( "" );
                    messageMapper.insertSelective( message );
                    SendJPushMessage.jPushByMessage( message );


                }
            } catch (Exception e) {
                e.printStackTrace();
            }

        }
    }
}
